package org.lucifer.task.ibatis.util;

import java.util.Date;

public class DateUtil {
	/**
	 * 输入一个Date类型对象，将其转换为String字符串格式，如：20150117
	 * @param date
	 * @return String字符串格式，如：20150117
	 */
	@SuppressWarnings("deprecation")
	public static String dateToString(Date date){
		String realYear=null;
		String realMonth=null;
		String realDate=null;
		
		realYear=String.valueOf(date.getYear()+1900);
		
		if(String.valueOf(date.getMonth()+1).length()!=2){
			realMonth="0"+String.valueOf(date.getMonth()+1);
		}else{
			realMonth=String.valueOf(date.getMonth()+1);
		}
		
		if(String.valueOf(date.getDate()).length()!=2){
			realDate="0"+String.valueOf(date.getDate());
		}else{
			realDate=String.valueOf(date.getDate());
		}
		
		return realYear+realMonth+realDate;
	}
	
	/**
	 * 输入一个String字符串对象，比如04/16/2015，将其转换为Date类型对象，如：Sat Jan 17 15:18:12 CST 2015
	 * @param date
	 * @return Date类型对象，如：Sat Jan 17 15:18:12 CST 2015
	 */
	@SuppressWarnings("deprecation")
	public static Date stringToDate(String date){
		int year;
		int month;
		int day;
		
		String[] dates=date.split("/");
		date=dates[2]+dates[0]+dates[1];
		
		year=Integer.parseInt(date.substring(0,4))-1900;
		
		if("0".equals(date.substring(4,5))){
			month=Integer.parseInt(date.substring(5,6))-1;
		}else{
			month=Integer.parseInt(date.substring(4,6))-1;
		}
		
		if("0".equals(date.substring(6))){
			day=Integer.parseInt(date.substring(6));
		}else{
			day=Integer.parseInt(date.substring(6,8));
		}
		
		return new Date(year,month,day);
	}
	
	/**
	 * 获取Date类型对象的year变量，需要+1900
	 * @param date
	 * @return year变量
	 */
	@SuppressWarnings("deprecation")
	public static int getYearFromDate(Date date){
		return date.getYear()+1900;
	}
	
	/**
	 * 获取Date类型对象的month变量，需要+1
	 * @param date
	 * @return month变量
	 */
	@SuppressWarnings("deprecation")
	public static int getMonthFromDate(Date date){
		return date.getMonth()+1;
	}
	
	/**
	 * 获取Date类型对象的date变量，直接返回
	 * @param date
	 * @return date变量
	 */
	@SuppressWarnings("deprecation")
	public static int getDateFromDate(Date date){
		return date.getDate();
	}
}
